import React, { useEffect, useRef, useState } from "react";
import { connect } from "react-redux";
import { CSSTransition } from "react-transition-group";

import styled from "styled-components";
import playerBg from "../../assets/images/player-bg.jpg";
import guide from "../../assets/images/guide.png";
import cdBg from "../../assets/images/cd-wrapper.png";
import micor from "../../assets/images/micor-phone.png";
import play from "../../assets/images/play.png";
import logo from "../../assets/images/logo.jpg";

import Comment from "../../components/Comment/comment.jsx";
import Lyric from "lyric-parser";

import { toggleFullScreen } from "./store/action";

function Player(props) {
  const { player } = props;
  const { fullScreen, currentSong } = player;
  const {
    name,
    picUrl,
    artists,
    album,
    alias,
    lrc,
    comments,
    url
  } = currentSong;
  const [pause, setPause] = useState(true); // 当前播放状态
  const fullRef = useRef(null);
  const audioRef = useRef(null);
  const [currTxt, setCurrTxt] = useState({});
  const lyricRef = useRef(null);
  const lrcWrapRef = useRef(null);

  const handleLyric = ({ lineNum, txt }) => {
    setCurrTxt({ lineNum, txt });
    lrcWrapRef.current.scrollTo({
      top: (lineNum - 1) * 32,
      lefet: 0,
      behavior: "smooth"
    });
  };
  const handleEnded = e => {
    console.log("播放完毕");
    lyricRef.current.seek(0);
    audioRef.current.play();
  };
  const togglePlay = () => {
    const dom = audioRef.current;
    if (url) {
      if (dom.paused) {
        setPause(false);
        dom.play();
        lyricRef.current && lyricRef.current.togglePlay();
      } else {
        setPause(true);
        dom.pause();
        lyricRef.current && lyricRef.current.togglePlay();
      }
    }
  };

  useEffect(() => {
    lyricRef.current && lyricRef.current.stop();
    setPause(true);
  }, [currentSong]);

  const handleCanPlay = e => {
    lyricRef.current = lrc && new Lyric(lrc.lyric, handleLyric);
    lyricRef.current && lyricRef.current.play();
    audioRef.current
      .play()
      .then(() => {
        setPause(false);
      })
      .catch(() => {
        lyricRef.current && lyricRef.current.togglePlay();
      });
  };

  return (
    <Wrap>
      <audio
        ref={audioRef}
        src={url}
        autoPlay
        style={{ display: "none" }}
        onCanPlayThrough={handleCanPlay}
        onEnded={handleEnded}
      ></audio>
      <CSSTransition
        in={fullScreen}
        timeout={300}
        classNames="fly"
        onEnter={() => {
          fullRef.current.style.display = "block";
        }}
        onExited={() => {
          fullRef.current.style.display = "none";
        }}
      >
        <FullPlayerWrapper
          style={{ display: "none" }}
          ref={fullRef}
          className="player"
          songBg={album?.blurPicUrl || album?.picUrl}
        >
          <div className="song-bg" style={{ filter: "blur(10px)" }}></div>
          <PlayContent>
            <div className="fst">
              <div className="m-guide">
                <i className="arr"></i>
              </div>
              <div className="CDWrapper">
                <div className={`disc ${pause ? "no" : ""}`}>
                  <div className="pic-wrap">
                    <div className="bg"></div>
                    <div className={`img play ${pause ? "pause" : "run"}`}>
                      <img
                        src={picUrl || album?.picUrl || cdBg}
                        alt={album?.name}
                      />
                    </div>
                  </div>
                  {pause ? <span className="plybtn"></span> : null}
                </div>
                <div className="clickarea" onClick={togglePlay}></div>
              </div>
              <div className="song-info">
                <p className="link">查看更多歌词</p>
                <h2 className="title">
                  {name} - {artists}
                </h2>
                <div className="lrc">
                  <div className="lrc-wrap" ref={lrcWrapRef}>
                    <div className="lrc-content">
                      {lyricRef.current &&
                        lyricRef.current.lines.map(({ time, txt }, index) => (
                          <p
                            key={index}
                            className={`lrc-item ${
                              txt == currTxt.txt ? "curr" : ""
                            }`}
                          >
                            {txt}
                          </p>
                        ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="new-comment">
              <h4 className="cmt-title">最新评论</h4>
              <Comment
                list={comments || []}
                theme={{
                  theme: "#fff",
                  l: "rgba(255,255,255,0.7)",
                  ll: "rgba(255,255,255,0.3)"
                }}
              />
            </div>
          </PlayContent>
        </FullPlayerWrapper>
      </CSSTransition>
      <MiniPlayerWrapper
        className="mini-player"
        onClick={props.toggleFullScreen.bind(this, !fullScreen)}
      >
        <div className={`img play ${pause ? "pause" : "run"}`}>
          <img src={picUrl || album?.picUrl || logo} alt="" />
        </div>
      </MiniPlayerWrapper>
    </Wrap>
  );
}
export default connect(state => ({ player: state.player }), {
  toggleFullScreen
})(React.memo(Player));

const Wrap = styled.div`
  @keyframes Dong {
    0% {
    }
  }
  .play {
    animation: roteta 10s infinite linear;
  }
  .pause {
    animation-play-state: paused;
  }
  .run {
    animation-play-state: running;
  }
  @keyframes roteta {
    0% {
      transform: rotate(0);
    }
    100% {
      transform: rotate(360deg);
    }
  }
`;
const MiniPlayerWrapper = styled.div`
  position: fixed;
  bottom: 30px;
  left: 30px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  z-index: 201;
  overflow: hidden;
  box-shadow: 0 0 3px 1px #d43c33;
  .img {
    width: 100%;
    height: 100%;
    img {
      &:active {
        transform: scale(1.5);
      }
      transition: all 0.5s;
      width: 100%;
      height: 100%;
      transform: scale(1.2) translate(-1px, 1px);
      border-radius: 50%;
      background: url(${logo}) no-repeat;
      background-size: contain;
    }
  }
`;
const PlayContent = styled.div`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 60px;
  overflow: auto;
  z-index: 21;
  .new-comment {
    position: relative;
    padding-top: 70px;
    color: #fff;
    .cmt-list {
      p {
        text-align: center;
      }
    }
    .cmt-title {
      font-weight: 400;
      position: relative;
      padding: 0 0 0 10px;
      line-height: 25px;
      font-size: 16px;
      background-color: rgba(0, 0, 0, 0);
    }
  }
  .fst {
    height: 607px;
    position: relative;
    padding-bottom: 12px;
    box-sizing: border-box;
    .song-info {
      padding: 0 35px;
      margin-top: 25px;
      .link {
        color: hsla(0, 0%, 100%, 0.6);
        height: 30px;
        line-height: 30px;
        position: absolute;
        left: 0;
        right: 0;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: center;
        bottom: 18px;
      }
      .lrc {
        position: relative;
        margin-top: 14px;
        .lrc-wrap {
          height: 86px;
          overflow: auto;
          color: hsla(0, 0%, 100%, 0.6);
          line-height: 1.5;
          .lrc-content {
            text-align: center;
            font-size: 16px;
            .lrc-item {
              padding-bottom: 8px;
              &.curr {
                color: #fff;
              }
            }
          }
        }
      }
      .title {
        text-align: center;
        font-size: 20px;
        line-height: 1.1;
        color: #fefefe;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
    .CDWrapper {
      padding-top: 70px;
      position: relative;
      .clickarea {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        z-index: 300;
      }
      .disc {
        width: 296px;
        height: 296px;
        margin: 0 auto;
        position: relative;
        .plybtn {
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          width: 56px;
          height: 56px;
          z-index: 200;
          background: url(${play}) no-repeat;
          background-size: contain;
        }
        &.no {
          &::after {
            transform: rotate(-20deg);
          }
        }
        &::after {
          content: "";
          width: 96px;
          position: absolute;
          height: 137px;
          top: -70px;
          left: 133px;
          background-image: url(${micor});
          background-size: contain;
          z-index: 100;
          transform-origin: top left;
          transition: transform 0.4s ease;
        }
        .pic-wrap {
          width: 100%;
          height: 100%;
          overflow: hidden;
          .img {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            img {
              width: 184px;
              height: 184px;
            }
          }
          .bg {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            z-index: 3;
            background: url(${cdBg}) no-repeat;
            background-size: cover;
          }
        }
      }
    }
    .m-guide {
      position: absolute;
      left: 0;
      right: 0;
      height: 36px;
      padding-top: 10px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      align-items: center;
      z-index: 10;
      margin-bottom: env(safe-area-inset-bottom);
      bottom: -14px;
      @keyframes shining {
        0% {
          background-position: 0 0;
        }
        15% {
          background-position: 0 -12px;
        }
        30% {
          background-position: 0 -24px;
        }
        45% {
          background-position: 0 -36px;
        }
        60% {
          background-position: 0 -48px;
        }
        75% {
          background-position: 0 -60px;
        }
        90% {
          background-position: 0 -72px;
        }
        100% {
          background-position: 0 -84px;
        }
      }
      .arr {
        width: 17px;
        height: 12px;
        display: block;
        background: url(${guide}) no-repeat;
        background-size: 17px auto;
        background-position: 0 0;
        animation: shining 1.2s steps(1) infinite;
      }
    }
  }
`;
const FullPlayerWrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
  background: #999;
  z-index: 100;
  transform-origin: bottom right;
  &.fly-enter,
  &.fly-appear {
    transform: translate3d(0, 30px, 0);
    opacity: 0;
  }
  &.fly-enter-active,
  &.fly-appear-active {
    transition: all 0.3s ease;
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  &.fly-exit {
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  &.fly-exit-active {
    transition: all 0.3s ease;
    transform: translate3d(0, 30px, 0);
    opacity: 0;
  }
  .song-bg {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: url(${props => props.songBg || playerBg});
    background-color: #161824;
    background-position: 50%;
    background-repeat: no-repeat;
    background-size: auto 100%;
    transform: scale(1.5);
    transform-origin: center top;
    &::after {
      content: " ";
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.5);
    }
  }
`;
const FullFooter = styled.div`
  background: none;
  z-index: 100;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 10px;
`;
